package com.example.application.views.admin;

import java.util.ArrayList;
import java.util.List;

import com.example.application.bean.PageBean;
import com.example.application.bean.ResultBean;
import com.example.application.bean.User;
import com.example.application.config.URLConfig;
import com.example.application.views.util.MyHttpClientUtil;
import com.example.application.views.util.ShowAllInfosUtil;
import com.example.application.views.util.DialogUtil;
import com.example.application.views.util.VerifyUtil;
import com.example.page.PageComponent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.HasStyle;
import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.gridpro.GridPro;
import com.vaadin.flow.component.html.Div;

import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.splitlayout.SplitLayout;
import com.vaadin.flow.data.binder.BeanValidationBinder;

import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.PageTitle;
import com.example.application.views.main.MainView;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.textfield.TextField;

@Route(value = "admin", layout = MainView.class)
//@RouteAlias(value = "", layout = MainView.class)
@PageTitle("用户管理")
@CssImport("./views/用户管理/用户管理-view.css")
public class AdminView extends Div {

    private GridPro<User> grid;

    private TextField loginName;
    private TextField telNum;
    private TextField email;
    private TextField name;
    private TextField identity;
    private TextField state;
    private Checkbox important;

    private Button cancel = new Button("Cancel");
    private Button save = new Button("Save");
    private Button add = new Button("new");
    private Button delete = new Button("delete");

    private BeanValidationBinder<User> binder;

    private User user;

    PageBean<User> pageBean;

    public AdminView() {
        User user = (User) UI.getCurrent().getSession().getAttribute("user");
        if (user == null){

        }else if("平台管理员".equals(user.getIdentity())){
            this.init();
        }else{
            DialogUtil.adminAuthority();
        }

    }

    private void createEditorLayout(SplitLayout splitLayout) {
        Div editorLayoutDiv = new Div();
        editorLayoutDiv.setId("editor-layout");

        Div editorDiv = new Div();
        editorDiv.setId("editor");
        editorLayoutDiv.add(editorDiv);

        FormLayout formLayout = new FormLayout();
        loginName = new TextField("用户名");
        telNum = new TextField("电话");
        email = new TextField("邮箱");
        name = new TextField("姓名");
        Component[] fields = new Component[]{loginName, name, email, telNum};

        for (Component field : fields) {
            ((HasStyle) field).addClassName("full-width");
        }
        formLayout.add(fields);
        editorDiv.add(formLayout);
        createButtonLayout(editorLayoutDiv);

        splitLayout.addToSecondary(editorLayoutDiv);
    }

    private void createButtonLayout(Div editorLayoutDiv) {
        HorizontalLayout buttonLayout = new HorizontalLayout();
        buttonLayout.setId("button-layout");
        buttonLayout.setWidthFull();
        buttonLayout.setSpacing(true);
        cancel.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
        save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        add.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        delete.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        buttonLayout.add(save, cancel);
        editorLayoutDiv.add(buttonLayout);
    }

    private void createGridLayout(SplitLayout splitLayout) {
        Div wrapper = new Div();
        wrapper.setId("grid-wrapper");
        wrapper.setWidthFull();

        PageComponent pageComponent = new PageComponent(pageBean.getCurrentPage(), pageBean.getPageSize(), pageBean.getTolNum(), pageBean.getTolPage()) {
            @Override
            protected void pageNext() {
                pageBean.setCurrentPage(this.curPage);
                pageBean.setPageSize(this.pageSize);
                updateForm(this.curPage, this.pageSize);
            }

            @Override
            protected void pagePrevious() {
                pageBean.setCurrentPage(this.curPage);
                pageBean.setPageSize(this.pageSize);
                updateForm(this.curPage, this.pageSize);
            }

            @Override
            protected void gotoPage() {
                pageBean.setCurrentPage(this.curPage);
                pageBean.setPageSize(this.pageSize);
                updateForm(this.curPage, this.pageSize);
            }

            @Override
            protected void firstPage() {
                pageBean.setCurrentPage(this.curPage);
                pageBean.setPageSize(this.pageSize);
                updateForm(this.curPage, this.pageSize);
            }

            @Override
            protected void lastPage() {
                pageBean.setCurrentPage(this.curPage);
                pageBean.setPageSize(this.pageSize);
                updateForm(this.curPage, this.pageSize);
            }

            @Override
            protected void selectPage() {
                pageBean.setCurrentPage(this.curPage);
                pageBean.setPageSize(this.pageSize);
                updateForm(this.curPage, this.pageSize);
            }
        };
        pageComponent.components.add(grid);
        pageComponent.init();
        splitLayout.addToPrimary(pageComponent);
    }

    private void refreshGrid() {
        grid.select(null);
        grid.getDataProvider().refreshAll();
    }

    private void clearForm() {
        populateForm(null);
    }

    private void populateForm(User value) {
        this.user = value;
        binder.readBean(this.user);
    }

    public void updateForm(int curPage, int pageSize){
        ResultBean<PageBean> resultBean = ShowAllInfosUtil.showInfos(URLConfig.USER_PAGE, curPage, pageSize, User.class);

        pageBean = resultBean.getT();

        grid.setItems(resultBean.getT().getDatas());
    }

    public void init(){
        grid = new GridPro<>();
        addClassName("用户管理-view");
        pageBean = new PageBean<>();
        pageBean.setCurrentPage(1);
        pageBean.setPageSize(3);
        // Create UI
        SplitLayout splitLayout = new SplitLayout();
        splitLayout.setSizeFull();

        updateForm(1, 3);
        createGridLayout(splitLayout);
        createEditorLayout(splitLayout);

        add(splitLayout);

        // Configure Grid
        grid.addColumn(User::getLoginName).setHeader("用户名").setAutoWidth(true);
        grid.addColumn(User::getName).setHeader("姓名").setAutoWidth(true);
        grid.addColumn(User::getEmail).setHeader("邮箱").setAutoWidth(true);
        grid.addColumn(User::getTelNum).setHeader("电话").setAutoWidth(true);
        grid.addColumn(User::getIdentity).setHeader("身份").setAutoWidth(true);
        List<String> optionsList = new ArrayList<>();
        optionsList.add("可用");
        optionsList.add("不可用");
        grid.addEditColumn(User::getState).select((item, newValue) ->
                item.setState(newValue), optionsList)
                .setHeader("状态");

//        TemplateRenderer<SamplePetOwner> importantRenderer = TemplateRenderer.<SamplePetOwner>of(
//                "<iron-icon hidden='[[!item.important]]' icon='vaadin:check' style='width: var(--lumo-icon-size-s); height: var(--lumo-icon-size-s); color: var(--lumo-primary-text-color);'></iron-icon><iron-icon hidden='[[item.important]]' icon='vaadin:minus' style='width: var(--lumo-icon-size-s); height: var(--lumo-icon-size-s); color: var(--lumo-disabled-text-color);'></iron-icon>")
//                .withProperty("important", SamplePetOwner::isImportant);
//        grid.addColumn(importantRenderer).setHeader("Important").setAutoWidth(true);
        grid.addThemeVariants(GridVariant.LUMO_NO_BORDER);
        grid.setHeightFull();

        // when a row is selected or deselected, populate form
        grid.asSingleSelect().addValueChangeListener(event -> {
            populateForm(event.getValue());
        });

        // Configure Form
        binder = new BeanValidationBinder<>(User.class);

        // Bind fields. This where you'd define e.g. validation rules

        binder.bindInstanceFields(this);

        cancel.addClickListener(e -> {
            clearForm();
            refreshGrid();
        });

        save.addClickListener(e -> {
            if(user != null){
                try {
                    //                保存修改的数据
                    String url = URLConfig.EDIT_USER;

                    user.setEmail(email.getValue().trim());
                    user.setLoginName(loginName.getValue().trim());
                    user.setName(name.getValue().trim());
                    user.setTelNum(telNum.getValue().trim());

                    if(!VerifyUtil.emailVerify(user.getEmail())){
                        UI.getCurrent().getPage().executeJs("alert('邮箱格式不正确')");
                    }else if(!VerifyUtil.lengthVerify(user.getName())){
                        UI.getCurrent().getPage().executeJs("alert('姓名长度不能超过10')");
                    }else if(!VerifyUtil.lengthVerify(user.getLoginName())){
                        UI.getCurrent().getPage().executeJs("alert('用户名长度不能超过10')");
                    }else if(!VerifyUtil.telePhoneNumVerify(user.getTelNum())){
                        UI.getCurrent().getPage().executeJs("alert('电话格式不正确')");
                    }else if("平台管理员".equals(user.getIdentity()) && "不可用".equals(user.getState())){
                        UI.getCurrent().getPage().executeJs("alert('平台管理员不能禁用')");
                    }else{

                        String msg = MyHttpClientUtil.httpPut(url, user, "utf8");
                        ObjectMapper mapper = new ObjectMapper();
                        JavaType javaType = mapper.getTypeFactory().constructParametricType(ResultBean.class, String.class);
                        ResultBean<String> resultBean = mapper.readValue(msg, javaType);

                        if(resultBean.getCode() == 0){
                            UI.getCurrent().getPage().executeJs("alert('保存失败')");
                        }else{
                            UI.getCurrent().getPage().executeJs("alert('保存成功')");
                        }
                    }
                    updateForm(pageBean.getCurrentPage(), pageBean.getPageSize());
                } catch (JsonProcessingException jsonProcessingException) {
                    jsonProcessingException.printStackTrace();
                }
            }
        });
    }

}
